package com.core.update;

import com.data.excel.FromExcel;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.CreateRequest;
import com.rallydev.rest.request.DeleteRequest;
import com.rallydev.rest.request.GetRequest;
import com.rallydev.rest.request.QueryRequest;
import com.rallydev.rest.request.UpdateRequest;
import com.rallydev.rest.response.CreateResponse;
import com.rallydev.rest.response.DeleteResponse;
import com.rallydev.rest.response.GetResponse;
import com.rallydev.rest.response.QueryResponse;
import com.rallydev.rest.response.UpdateResponse;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import com.rallydev.rest.util.Ref;

import java.io.IOException;

import java.net.URI;
import java.net.URISyntaxException;

public class restTestResultsUpdate {
	  public static void updateRally(String username, String password, String testCaseId, String verdict, String notes, String build, String testSet ) throws URISyntaxException, IOException {
	// Create and configure a new instance of RallyRestApi         
	RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"),username, password);
	restApi.setWsapiVersion("1.37");         
	restApi.setApplicationName("Add Test Case Result");     

	String workspaceRef = "/workspace/QES";
	String projectRef = "/project/Stingray";

	
	//Query User         
	QueryRequest userRequest = new QueryRequest("User");         
	userRequest.setFetch(new Fetch("UserName", "Subscription", "DisplayName"));         
	userRequest.setQueryFilter(new QueryFilter("UserName", "=", username));         
	QueryResponse userQueryResponse = restApi.query(userRequest);         
	JsonArray userQueryResults = userQueryResponse.getResults();         
	JsonElement userQueryElement = userQueryResults.get(0);         
	JsonObject userQueryObject = userQueryElement.getAsJsonObject();         
	String userRef = userQueryObject.get("_ref").toString();          
	// Query for Test Case to which we want to add results         
	QueryRequest testCaseRequest = new QueryRequest("TestCase");         
	testCaseRequest.setFetch(new Fetch("FormattedID","Name"));         
	testCaseRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testCaseId));   
	testCaseRequest.setWorkspace(workspaceRef);
	//testCaseRequest.setProject(projectRef);
	QueryResponse testCaseQueryResponse = restApi.query(testCaseRequest);         
	JsonObject testCaseJsonObject = testCaseQueryResponse.getResults().get(0).getAsJsonObject();         
	String testCaseRef = testCaseQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();   

	/*QueryRequest testProjectRequest = new QueryRequest("Project");
	testProjectRequest.setFetch(new Fetch("FormattedID", "Name"));
	testProjectRequest.setQueryFilter(new QueryFilter("Name", "=", "Stingray"));
	testProjectRequest.setWorkspace(workspaceRef);
	QueryResponse testProjectQueryResponse = restApi.query(testProjectRequest);
	JsonObject testProjectJsonObject = testProjectQueryResponse.getResults().get(0).getAsJsonObject();     
	String testProjRef = testProjectQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString();
	*/
	/*QueryRequest testIterationRequest = new QueryRequest("Iteration");
	testIterationRequest.setFetch(new Fetch("FormattedID", "Name", "Project"));
	//TODO hard coded iteration
	QueryFilter nameFilter = new QueryFilter("Name", "=", iteration);
	QueryFilter iterationFilter = new QueryFilter("Project.Name", "=", "Stingray");
	testIterationRequest.setQueryFilter(nameFilter.and(iterationFilter)); 
	testIterationRequest.setWorkspace(workspaceRef);
	//testIterationRequest.setProject(projectRef);
	QueryResponse testIterationQueryResponse = restApi.query(testIterationRequest);
	String testIterationRef = testIterationQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString(); 
	System.out.println("TestIteration object: "+testIterationRef);*/
	String testSetRef = null;
	if(testSet!=""){
	// Query for Test Set to which we want to add results  
	QueryRequest testsetRequest = new QueryRequest("TestSet"); //no spaces
	testsetRequest.setFetch(new Fetch("FormattedID","Name" ));     
	//No need to specify type again 
	testsetRequest.setQueryFilter(new QueryFilter("FormattedID", "=", testSet));
	testsetRequest.setWorkspace(workspaceRef);
	//testsetRequest.setProject(projectRef);
	QueryResponse testSetQueryResponse = restApi.query(testsetRequest);
	//JsonObject testSetJsonObject = testSetQueryResponse.getResults().get(0).getAsJsonObject();         
	testSetRef = testSetQueryResponse.getResults().get(0).getAsJsonObject().get("_ref").toString(); 
	}
	//System.out.println("TestSet object: "+testSetRef);
	try{             
		//Add a Test Case Result             
		System.out.println("Creating Test Case Result...");             
		JsonObject newTestCaseResult = new JsonObject();             
		newTestCaseResult.addProperty("Verdict", verdict);             
		newTestCaseResult.addProperty("Date", FromExcel.getCurrentDateAndTime());      
		if(notes!=""){
		newTestCaseResult.addProperty("Notes", notes);  
		}
		newTestCaseResult.addProperty("Build", build);     
		if(testCaseRef!=null){
		newTestCaseResult.addProperty("TestSet", testSetRef);
		}
		newTestCaseResult.addProperty("Tester", userRef);             
		newTestCaseResult.addProperty("TestCase", testCaseRef); 
		
		CreateRequest createRequest = new CreateRequest("testcaseresult", newTestCaseResult);             
		CreateResponse createResponse = restApi.create(createRequest);              
		if(createResponse.wasSuccessful()){                 
			//System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
			System.out.println("Created Result for: "+ testCaseId);
			//Read Test Case                 
			String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString()); 
			//System.out.println(String.format("\nReading Test Case Result %s...", ref));                 
			System.out.println(String.format("\nReading Test Case Result ..."));
			GetRequest getRequest = new GetRequest(ref);                 
			getRequest.setFetch(new Fetch("Date", "Verdict"));                 
			GetResponse getResponse = restApi.get(getRequest);                 
			JsonObject obj = getResponse.getObject();                 
			System.out.println(String.format("Read Test Case Result. Date = %s, Verdict = %s", obj.get("Date").getAsString(), obj.get("Verdict").getAsString()));
			} else {  
				String[] createErrors;                 
				createErrors = createResponse.getErrors();                 
				System.out.println("Error occurred creating Test Case: ");                 
				for (int i=0; i<createErrors.length;i++) 
				{                     
					System.out.println(createErrors[i]);                 
					}             
				}          
		}
	catch(Exception e){
		System.out.println("Error"+e.getMessage());
	}
	finally{     
		
		restApi.close();         
		}      
		}

	}

